﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TsCore;

namespace TsWeb.Sports
{
    public partial class ManageTeams : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                BindTeams();
        }

        private void BindTeams()
        {
            TeamsGrid.DataSource = TsSystem.Instance.GetAllTeams();
            TeamsGrid.DataBind();
            TeamsGrid.UseAccessibleHeader = true;
            if (TeamsGrid.HeaderRow != null)
            {
                TeamsGrid.HeaderRow.TableSection = TableRowSection.TableHeader;
            }            
           
        }

        protected void ButtonCreateTeam_Click(object sender, EventArgs e)
        {
            UserButton.Text = "Crear equipo";
            Session["Action"] = "Create";
            List <Comment> NewTeamComments =  new List<Comment>();
            Session["TeamComments"] = NewTeamComments;
            //Creo lista de comentarios vacia
            ListViewComments.DataSource = NewTeamComments;
            ListViewComments.DataBind();
            CleanUserForm();
            SportComboBox.DataSource = TsSystem.Instance.GetAllSports();
            SportComboBox.DataBind();

            //ModalPopupExtender1.Show();
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "$('#myModal').modal('show');", true);
        }

        protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            if (AsyncFileUpload1.HasFile)
            {
                string filepath = MapPath("~/Sports/Logos/") + System.IO.Path.GetFileName(e.FileName);
                AsyncFileUpload1.SaveAs(filepath);
                string newImageUrl = "~/Sports/Logos/" + e.FileName;
                string newImageSrc = "Logos/" + e.FileName;                
             
                Session["TeamLogoUrl"] = newImageUrl;
                displayTeamLogo(newImageSrc);
            }
        }

        protected void UpdateTeamButton_Click(object sender, EventArgs e)
        {
            string opt = Session["Action"].ToString();
            switch (opt)
            {
                case "Create":
                    {
                        string teamName = TeamNameTxt.Text;
                        //sustituir por control de JP
                        string ImageUrl = (String)Session["TeamLogoUrl"];
                        if (ImageUrl == null)
                        {
                            ImageUrl = "~/Sports/Logos/defaultSport.jpg";
                        }
                        Sport teamSport = TsSystem.Instance.GetSport(Int32.Parse(SportComboBox.SelectedItem.Value));

                        TsSystem.Instance.CreateNewTeam(teamName, ImageUrl, (List<Comment>)Session["TeamComments"], teamSport);
                        break;
                    }
                case "Update":
                    {
                        Team updatedTeam = (Team)Session["UpdatedTeam"];
                        updatedTeam.Name = TeamNameTxt.Text;
                        updatedTeam.Comments = (List<Comment>)Session["TeamComments"];
                        updatedTeam.Sport = TsSystem.Instance.GetSport(Int32.Parse(SportComboBox.SelectedItem.Value));
                        updatedTeam.Image = (String)Session["TeamLogoUrl"];
                        TsSystem.Instance.UpdateTeam(updatedTeam);
                        break;
                    }

            }
            BindTeams();
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call m1e", "$('#myModal').modal('hide');", true);
        }

        protected void TeamsGrid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = TeamsGrid.Rows[index];
            int TeamId = Convert.ToInt32(row.Cells[0].Text);
            if (e.CommandName == "EditCommand")
            {
                Team team = TsSystem.Instance.GetTeam(TeamId);
                TeamNameTxt.Text = team.Name;
                List<Sport> toBindSports = TsSystem.Instance.GetAllSports();
                SportComboBox.DataSource = toBindSports;
                SportComboBox.DataBind();
                SportComboBox.SelectedIndex = toBindSports.IndexOf(team.Sport);
                SportComboBox.Enabled = true;
                if (TsSystem.Instance.GetMatchesForTeam(team).Count > 0)
                {
                    SportComboBox.Enabled = false;
                }
                Session["TeamComments"] = team.Comments;
                UserButton.Text = "Actualizar deporte";
                Session["Action"] = "Update";
                Session["UpdatedTeam"] = team;
                Session["TeamLogoUrl"] = team.Image;
                displayTeamLogo(team.Image.Remove(0,9));
                if (team.Image != null)
                {
                    Session["TeamLogoUrl"] = team.Image;
                    displayTeamLogo(team.Image.Remove(0, 9));
                }
                else
                {
                    Session["TeamLogoUrl"] = "~/Sports/Logos/defaultSport.jpg";
                }
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "$('#myModal').modal('show');", true);
            }
            if (e.CommandName == "DeleteCommand")
            {
                //TODO: Hacer que aparezca una confirmacion y que se actualizce la lista luesgo de hacer el borrado
                Team team = TsSystem.Instance.GetTeam(TeamId);
                TsSystem.Instance.RemoveTeam(team);

            }
            if (e.CommandName == "CommentCommand")
            {
                
                Team team = TsSystem.Instance.GetTeam(TeamId);
                Session["TeamComments"] = team.Comments;
                Session["UpdatedTeam"] = team;
                ListViewComments.DataSource = team.Comments;
                ListViewComments.DataBind();
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "$('#ModalComentarios').modal('show');", true);

            }


        }

        private void CleanUserForm()
        {
            TeamNameTxt.Text = "";

        }

        /*protected void ListViewComments_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            TextBox txtComent = (TextBox)e.Item.FindControl("TeamCommentTextBox");
            
            List<Comment> comments = (List<Comment>)Session["TeamComments"];
            Comment newComment = new Comment();
            newComment.CmtDate = DateTime.Now;
            newComment.Text = txtComent.Text;
            comments.Add(newComment);
            ListViewComments.DataSource = comments;
            ListViewComments.DataBind();



            string ImageUrl = Session["TeamLogoUrl"].ToString().Remove(0, 9);
            displayTeamLogo(ImageUrl);
      
            //ModalPopupExtender1.Show();
            

        }*/

        protected void CommentTeamButton_Click(object sender, EventArgs e)
        {
            List<Comment> comments = (List<Comment>)Session["TeamComments"];
            Comment newComment = new Comment();
            newComment.CmtDate = DateTime.Now;
            newComment.Text = TeamCommentTextBox.Text;
            comments.Add(newComment);
            Team updatedTeam = (Team)Session["UpdatedTeam"];
            TsSystem.Instance.UpdateTeam(updatedTeam);
            ListViewComments.DataSource = comments;
            ListViewComments.DataBind();


        }


        private void displayTeamLogo(String ImageUrl)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "imageSrc", "top.$get(\"" + TeamLogo.ClientID + "\").src = '" + ImageUrl + "';", true);
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "imageDisplay", "top.$get(\"" + TeamLogo.ClientID + "\").style.display = '';", true);
        }
    }
}
